/* 
 * Copyright 2013 Imanuel Rohlfing, Dennis Wittkötter

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package management.beans;


import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.el.ELContext;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import management.constants.Names;
import management.ejb.DatabaseController;
import management.entities.Person;
import management.entities.Room;


/**
 * Bean for Room objects.
 * This bean handles the database operations with the Room entities.
 * @author Dennis Wittkötter
 */
@ManagedBean(name="rooms")
@SessionScoped
public class RoomBean implements Serializable {
    /**
     * database controller
     */
    @EJB
    private DatabaseController dbC;
    
    /**
     * current room object
     */
    private Room current = new Room();
    
    /**
     * a list of all rooms stored in the database
     */
    private List<Room> allRooms;
    
    /**
     * a picklist of persons
     */
    private PersonPickListBean personPickListB;
    
    /**
     * a LoginBean
     */
    private LoginBean loginBean;  
    
    
    
    /**
     * Default constructor
     */
    public RoomBean() {
        personPickListB = (PersonPickListBean)getBean("personPickList", PersonPickListBean.class);
        loginBean = (LoginBean)getBean("auth", LoginBean.class);
    }
    
    /**
     * Loads all rooms from database into a local field.
     */
    @PostConstruct
    public void loadRoomList() {
        allRooms = dbC.getRooms();
    }    
    
    /**
     * Persists a room object to the database.
     * @param r room to persist
     * @return  link path for website redirection
     */
    public String add(Room r){
        if(!loginBean.isLoggedIn()){
            return "LOGIN";
        }
        try {
            if(dbC.roomExists(r)){
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, Names.MSG_ROOM_ALREADY_EXIST, ""));
            }
            else if( dbC.persist(r) ){
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, Names.MSG_ROOM_CREATED_S, ""));
                loadRoomList();
            }
            else{
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, Names.MSG_ROOM_CREATED_F, ""));                 
            }
        } 
        catch(Exception e) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, Names.MSG_ROOM_CREATED_F, ""));
        }    
        r.setName(null);
        r.setBuilding(null);
       
        return "SHOW_ROOM";
    }   

    /**
     * Updates the current room in the database.
     * @return  link path for website redirection
     */
    public String edit(){
        if(!loginBean.isLoggedIn()){
            return "LOGIN";
        }
        try{
            if(dbC.roomExists(current)){
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, Names.MSG_ROOM_ALREADY_EXIST, ""));
                return "EDIT_ROOM";
            }
            
            personPickListB.save();
            
            for(Person person : dbC.getPersons()) {
                person.removeRoom(current);
                dbC.update(person);
            }

            for(Person person : current.getPersons()) {
                person.setRoom(current);
                dbC.update(person);
            }               
            
            
            if( dbC.update(current) ){
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, Names.MSG_ROOM_EDITED_S, ""));
                loadRoomList();
                current = new Room();                    
            }
            else{
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, Names.MSG_ROOM_EDITED_F, ""));
                return "EDIT_ROOM";
            }
        }
        catch(Exception e){            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, Names.MSG_ROOM_EDITED_F, ""));
            return "EDIT_ROOM";
        }
        return "SHOW_ROOM";
    }
    
    /**
     * Reads the id of a room from the current request parameter and searches 
     * for the relates room in database. If found the room will be updated.
     * @return  link path for website redirection
     */
    public String gotoEdit() {
        String id = getRequestParameter("edit");
        current = dbC.findRoom(id);
        if(current == null){
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, Names.MSG_ROOM_DOESNT_EXIST, ""));
            return "SHOW_ROOM";
        }
        personPickListB.setCurrentRoom(current);
        
        return "EDIT_ROOM";
    }
    
    /**
     * Reads the id of a room from the current request parameter and searches 
     * for the relates room in database. If found the room will be deleted.
     * @return  link path for website redirection
     */
    public String gotoDelete() {
        if(!loginBean.isLoggedIn()){
            return "LOGIN";
        }
       
        for(Person person : dbC.getPersons()) {
            person.removeRoom(current);
            dbC.update(person);
        }        
        
        if( dbC.delete(current) ){
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, Names.MSG_ROOM_DELETED_S, ""));
            loadRoomList();
            current = new Room();
            return "SHOW_ROOM";
        }
        else{
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, Names.MSG_ROOM_DELETED_F, ""));
            return "EDIT_ROOM";
        }
    }  
       
    /**
     * Static method to get access to extern components.
     * @param <T>   type of the object of the component
     * @param beanName  name of the bean to get access on
     * @param clazz class of the bean to get access on
     * @return  the bean object to get access on
     */
    public static <T> T getBean(final String beanName, final Class<T> clazz) {
        ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        return (T) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, beanName);
    }   
    
    /**
     * Provides the value of the current request parameter.
     * @param par   faces parameter to read out
     * @return  value of the parameter
     */
     private String getRequestParameter(String par) { 
        return FacesContext.getCurrentInstance().getExternalContext()
                .getRequestParameterMap().get(par); 
    }
    
    /**
     * Provides the current room.
     * @return  object of current room
     */
    public Room getCurrent(){
        return current;
    }
    
    /**
     * Provides all rooms stored in the database.
     * @return  a list of all rooms
     */
    public List<Room> getRooms(){
        return allRooms;
    }
}
